package device

import (
	"common/logging"
	"iot/iot_app_server/app/db"
	"iot/iot_app_server/app/util"
	"net/http"
	"time"
)

func HandleGetDeviceStatus(w http.ResponseWriter, req *http.Request) {

	//解决跨域问题
	sTime := time.Now()
	w.Header().Add("Access-Control-Allow-Origin", "*")
	rmap := make(map[string]interface{})

	payloadInfo := &util.PayloadInfo{}
	_, err := util.GetReqBody(req, payloadInfo)
	if err != nil {
		w.Write(util.LogGetResponseString(req, sTime, payloadInfo.Msgid, util.ERR_CODE_PARA_ERROR, rmap))
		logging.Error("HandleGetDeviceStatus para error 1,GetReqBody failed,request=%v", req.Form)
		return
	}

	deviceid := payloadInfo.Deviceid

	if deviceid == "" {
		w.Write(util.LogGetResponseString(req, sTime, payloadInfo.Msgid, util.ERR_CODE_PARA_ERROR, rmap))
		logging.Error("HandleGetDeviceStatus para error 1,request=%v", req.Form)
		return
	}

	b_online, err := db.GetDeviceStatus(deviceid)
	if err != nil {
		w.Write(util.LogGetResponseString(req, sTime, payloadInfo.Msgid, util.ERR_CODE_DB_ERROR, rmap))
		logging.Error("HandleGetDeviceStatus db 1,request=%v", req.Form)
		return
	}
	rmap["online"] = b_online
	if deviceid == "1111" {
		rmap["name"] = "空调"
		rmap["info"] = "空调"+deviceid
		rmap["bind_time"] = "2017-05-01 14:57:13"
	}else if deviceid == "testuser" {
		rmap["name"] = "洗衣机"
		rmap["info"] = "洗衣机1112"
		rmap["bind_time"] = "2017-05-02 11:57:13"
	}else if deviceid == "testuser001" {
		rmap["name"] = "冰箱"
		rmap["info"] = "冰箱001"
		rmap["bind_time"] = "2017-05-04 09:23:42"
	}else if deviceid == "testuser002" {
		rmap["name"] = "冰箱"
		rmap["info"] = "冰箱002"
		rmap["bind_time"] = "2017-05-04 09:23:42"
	}else if deviceid == "testuser003" {
		rmap["name"] = "冰箱"
		rmap["info"] = "冰箱003"
		rmap["bind_time"] = "2017-05-04 09:23:42"
	}else if deviceid == "testuser004" {
		rmap["name"] = "冰箱"
		rmap["info"] = "冰箱004"
		rmap["bind_time"] = "2017-05-04 09:23:42"
	}
	

	rmap["deviceid"] = deviceid

	w.Write(util.LogGetResponseString(req, sTime, payloadInfo.Msgid, util.ERR_CODE_SUCCESS, rmap))
	logging.Debug("HandleGetSnByDeviceid ok ,request=%v", req.Form)

}
